const {User} = require('../models')
const crud = require('../utils')
let jwt = require('jsonwebtoken')

//token校验
const verify = async (ctx)=>{
  let token = ctx.headers.authorization
  token = token.replace('Bearer ','')
  try {
    let result =  jwt.verify(token,'jwt-token-demo')
    await User.findOne({_id:result._id}).then(res=>{
      if(res){
        ctx.body = {
          code:200,
          msg:'用户认证成功',
          user:res
        }
      }else{
        ctx.body = {
          code:500,
          msg:'用户认证失败',
        }
      }
    }).catch(err=>{
      ctx.body = {
        code:500,
        msg:'用户认证失败',
      }
    })
  } catch (error) {
    ctx.body = {
      code:500,
      msg:'用户认证失败',
    }
  }
}

//登录
const login = async (ctx)=>{
  let {username, password} = ctx.request.body
  await User.findOne({username,password}).then(res=>{
    if(res){
      let token = jwt.sign({username:res.username,_id:res._id},"jwt-token-demo",{expiresIn:3600*24*7})
      ctx.body = {
        code:200,
        msg:'登录成功',
        token
      }
    }else{
      ctx.body = {code:300,msg:'用户名或密码错误'}
    }
  }).catch(err=>{
    ctx.body = {
      code:500,
      msg:'登录出现异常',
      err
    }
  })
}
//注册
const register = async (ctx)=>{
  let {username, password} = ctx.request.body
  let isDouble = false
  await User.findOne({username}).then(res=>{
    //已经被注册了
    console.log(res,'-------------------');
    if(res)isDouble  = true
  })
  if(isDouble){
     ctx.body = {
      code:300,
      msg:'用户名已存在'
    }
    return
  }
    await crud.add(User,{username,password},ctx)
}
//修改密码
const updatePwd = async (ctx)=>{
  let {username, password} = ctx.request.body
  await User.updateOne({username},{password}).then(res=>{
    console.log(res,11111111111111);
    if(res.matchedCount>0){
      ctx.body = {
        code:200,
        msg:'密码修改成功'
      }
    }else{
      ctx.body = {
        code:300,
        msg:'密码修改失败'
      }
    }
  }).catch(err=>{
    ctx.body = {
      code:500,
      msg:'密码修改异常',
      err
    }
  })
}

//添加用户
const add = async (ctx)=>{
  let {username, password} = ctx.request.body
  await crud.add(User,{username,password},ctx)
}

const update = async (ctx)=>{
  let {_id} = ctx.request.body
  let {username,password} = ctx.request.body
  //第一个参数 ：通过什么属性选择（id） 第二个修改的内容
  await crud.update(User,({_id},{username,password}),ctx)
}

const del = async (ctx)=>{
  let {_id} = ctx.request.body
  await crud.del(User,{_id},ctx)
}

const find = async (ctx)=>{
  await crud.find(User,null,ctx)
}

const findOne = async (ctx)=>{
  let {_id} = ctx.request.query
  await crud.findOne(User,{_id},ctx)
}



module.exports = {
  verify,
  login,
  register,
  updatePwd,
  add,
  update,
  del,
  find,
  findOne
  
}